package com.ruoyi.core.config.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.WxUser;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import org.apache.commons.lang3.StringUtils;

/**
 * 微信登录授权工具类
 * @作者：xie
 * @时间：2022/8/28 10:29
 */
public class WxUtil {
    public static UserVo getUserVoByToken(){
        try{
            Long userId = LoginHelper.getUserId();
            if(ObjectUtil.isNotNull(userId)){
                return SpringUtils.getBean(IUserService.class).queryById(userId);
            }
        }catch (Exception e){
            System.out.println("token失效");
        }
        return null;
    }


    public  static void refreshWxUser(UserVo userVo, Boolean needLogin){
        WxUser wxUser = BeanUtil.toBean(userVo, WxUser.class);//转回wxuser
        wxUser.setUserId(userVo.getId());
        wxUser.setUsername(userVo.getNickname());
        wxUser.setUserType(UserType.APP_USER.getUserType());
        if(needLogin){
            LoginHelper.loginByDevice(wxUser,"0".equals(userVo.getUtype()) ? DeviceType.MP:DeviceType.XCX);
        }else {
            LoginHelper.setLoginUser(wxUser);
        }
    }

    public static R<LoginVo> authMsg(UserVo userVo){
        if(StringUtils.isBlank(userVo.getNickname())){
            return R.fail("非首次未授权",new LoginVo(StpUtil.getTokenValue(),userVo,"0"));
        }
        return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo,"0"));
    }
}


